package com.itheima.reggie.interceptor;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if(empId != null){
        //后端用户已登录 放行
            BaseContext.setCurrentId(empId);
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");

        if(userId != null){

            //将登录id 放到本地线程
            BaseContext.setCurrentId(userId);
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //未登录 则不放行
        return false;

    }
}
